package fr.emse.tatiana.importexport;


import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;


import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.IOverwriteQuery;
import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
import org.eclipse.ui.wizards.datatransfer.ImportOperation;

import fr.emse.tatiana.corpus.Corpus;





public class ImportCorpusWizard extends Wizard implements INewWizard, IOverwriteQuery{

	ImportCorpusMainPage choosezip;
	private String path;
   // String workspacepath=ResourcesPlugin.getWorkspace().getRoot().getLocation().toPortableString();
    List fileSystemObjects = new ArrayList();
    boolean yesToAll=false;
    boolean noToAll=false;
	boolean quit=false;
    
	public ImportCorpusWizard() {
		super();	
	}

	public void addPages() {
		choosezip = new ImportCorpusMainPage();
		addPage(choosezip);
	}
	@Override
	public boolean performFinish() {

		
        try {
            ZipFile zipFile = new ZipFile(path);
            
            String newcorpus=null;
            ZipLeveledStructureProvider sp = new ZipLeveledStructureProvider(zipFile);
            
            Object projectentry=null;
            List l = sp.getChildren(sp.getRoot());
    		for (Object o : l) {
    			if (sp.getChildren(o)!= null) {
    				newcorpus=sp.getLabel(o);
    				projectentry=o;
    			}
    		}
    		if (projectentry==null) return false; //TODO error message
    		
            IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(newcorpus);

            if (!project.exists()) {
            	try {
					project.create(null);
					project.open(null);
					project.refreshLocal(IResource.DEPTH_INFINITE, null);
				} catch (CoreException e) {
					e.printStackTrace();
				}
			}
			List filelist = ajouterFichier(sp,sp.getRoot());
			if(quit)
				return true;
			ImportOperation importop=new ImportOperation(ResourcesPlugin.getWorkspace().getRoot().getFullPath(),projectentry,sp,this,filelist); 
			importop.setOverwriteResources(true);
            importop.run(null); // TODO progress monitor
        } catch (ZipException e) {
            displayErrorDialog("Doesn't seem to be a Tatiana corpus file");
        } catch (IOException e) {
            displayErrorDialog("Couldn't read file");
        } catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		
		return true;
	}
	
	private List ajouterFichier(ZipLeveledStructureProvider sp,Object root){
		
		List ret = new Vector();
		List l = sp.getChildren(root);
		if (l==null) {
			if (sp.getLabel(root).startsWith(".")) return ret;
			IFile f = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(sp.getFullPath(root)));
			if (f.exists()) {
				if(yesToAll){
					yesToAll=true;
                	ret.add(root);
                	return ret;
				}
				else if(noToAll){
					return ret;
				}
				else{
					MessageDialog dialog = new MessageDialog(getContainer()
							.getShell(), IDEWorkbenchMessages.Question,
							null,"Do you want to overwrite file "+sp.getFullPath(root), MessageDialog.QUESTION, new String[] {
						IDialogConstants.YES_LABEL,
						IDialogConstants.YES_TO_ALL_LABEL,
						IDialogConstants.NO_LABEL,
						IDialogConstants.NO_TO_ALL_LABEL,
						IDialogConstants.CANCEL_LABEL }, 0);
					dialog.open();
					if(dialog.getReturnCode()==0){
						ret.add(root);
					}
					else if(dialog.getReturnCode()==1){
						yesToAll=true;
						ret.add(root);
					}
					else if(dialog.getReturnCode()==3){
						noToAll=true;
					}
					else if(dialog.getReturnCode()==4){
						quit=true;
						noToAll=true;
					}
					else if(dialog.getReturnCode()==-1){
						quit=true;
						noToAll=true;
					}

					return ret;
				}
			}
			ret.add(root);
		} else { // add all children of this folder
			for (Object o : l) {
				List toadd = ajouterFichier(sp,o);
				
				if (toadd.size() == 1) { // add associated hidden files
					String name = sp.getLabel(o);
					for (Object sib : l) {
						if (Corpus.isAssociatedFile(name, sp.getLabel(sib))) {
							ret.add(sib);
						}
					}
				}
				
				ret.addAll(toadd);
			}
		}
		return ret;
	}
	

	public void init(IWorkbench workbench, IStructuredSelection selection) {
		// TODO Auto-generated method stub
		
	}



	public void setPath(String path) {
		this.path=path;
		
	}


    
    /**
     * Display an error dialog with the specified message.
     *
     * @param message the error message
     */
    protected void displayErrorDialog(String message) {
        MessageDialog.openError(getContainer().getShell(),
                "Could not import corpus", message);
    }
    
    public String queryOverwrite(String pathString) {
		return null;

    }
	
}
